package com.hdsx.jxcsxm.utile;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;

/**
 * @author 占贤银
 * time 2023/3/10 9:28
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class HDFreeMarker {
    private static Logger logger = LoggerFactory.getLogger(HDFreeMarker.class);

    private Configuration configuration;

    private String templateName;

    private String fileName;

    private String filePath;

    public static Logger getLogger() {
        return logger;
    }

    public static void setLogger(Logger logger) {
        HDFreeMarker.logger = logger;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public String getTemplateName() {
        return templateName;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public void createJsonFile(HashMap<String,Object> map, String filePath, String fileName) {
        Template t = null;
        Writer out = null;
        try {
            //获取模板信息
            t = configuration.getTemplate(filePath);
            File outFile = new File(fileName);
            out = new BufferedWriter
                    (new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            //输出数据到模板中，生成文件。
            t.process(map, out, ObjectWrapper.BEANS_WRAPPER);
            out.close();
            logger.info(fileName + "生成成功!"+outFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public HDFreeMarker(String templatePath) {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(),templatePath);
    }
}
